var express = require('express');
const query = require('../config/db');
var router = express.Router();

// 同课程的相关接口
// 同步课程--地区数据
router.get("/getData",async(req,res,next)=>{
    let sql = `select * from e_area`
    let result = await query(sql)
    res.send({
        success:true,
        msg:"查询成功",
        status:200,
        data:result
    }) 
})
// 同步课程--年级数据
router.get("/getGrade",async(req,res,next)=>{
    let sql = `select * from e_grade`
    let result = await query(sql)
    res.send({
        success:true,
        msg:"查询成功",
        status:200,
        data:result
    })
})
// 同步课程--学科数据
router.get("/getSubject",async(req,res,next)=>{
    let sql = `select * from e_subject`
    let result = await query(sql)
    res.send({
        success:true,
        msg:"查询成功",
        status:200,
        data:result
    })
})
// 同步课程--考试类名
router.get("/getCate",async(req,res,next)=>{
    let sql = `select * from e_category`
    let result = await query(sql)
    res.send({
        success:true,
        msg:"查询成功",
        status:200,
        data:result
    })
})

// 同步课程--课程接口
// 分页逻辑
router.get("/course",async(req,res,next)=>{
    // 传递过来的参数需要一个默认值
    let {page = 1,size = 10,area = '',grade = '',subject = '',cate = ''} = req.query
    // 需要先给变量一个默认值，后续使用
    let whereStr = ''
    // 地区的判断
    if(whereStr === ''){
        if(area !== ''){
        whereStr += ` where area_name='${area}'`
        }
    }else{
        if(area !== ''){
            whereStr += ` and area_name='${area}'`
        }
    }

    // 年级的判断
    if(whereStr === ''){
        if(grade !== ''){
            whereStr += ` where grade_name='${grade}'`
        }
    }else{
        if(grade !== ''){
            whereStr += ` and grade_name='${grade}'`
        }
    }
    // 学科的判断
    if(whereStr === ''){
        if(subject !== ''){
            whereStr += ` where subject_name='${subject}'`
        }
    }else{
        if(subject !== ''){
            whereStr += ` and subject_name='${subject}'`
        }
    }
    // 类别
    if(whereStr === ''){
        if(cate !== ''){
            whereStr += ` where category_name='${cate}'`
        }
    }else{
        if(cate !== ''){
            whereStr += ` and category_name='${cate}'`
        }
    }

    page = Number(page)
    size = Number(size)
    // 为了读取出所有的结果，可能需要
    let sql1 = `select * from e_course${whereStr}`
    let result1 = await query(sql1)
    let totalPage = Math.ceil(result1.length/size)
    let totalNum  = result1.length
    
    // 限制页数分页
    let sql2 = `select * from e_course${whereStr} limit ${(page-1) * size},${size}`
    let result2 = await query(sql2)

    res.send({
        success:true,
        msg:"查询成功",
        status:200,
        data:{
            totalNum,
            totalPage,
            list:result2,
            page
        }
    })
})
module.exports = router